# coding: utf-8
"""
@python version : python3.10
@file name      : app03.py
@date           : 2024/5/15 13:35
@author         : ziyang.yang@aliyun.com
@gitee          : https://gitee.com/ziyangyang1318
@blog           : blog.yangziyang.top
@describe       : 
"""

from typing import Optional, List
from pydantic import BaseModel, Field, validator, ValidationError
from fastapi import APIRouter

app03 = APIRouter()


class Addr(BaseModel):
    city: str = "北京"
    street: str = "长安街"


class User(BaseModel):
    name: str = 'root'  # 校验传入的字段类型,并给一个默认值
    age: int = Field(default=18, gt=0, lt=100)  # 对年龄进行限制
    hobby: List[int] = []
    addr: Addr  # 可以接受类字段模型进行格式化校验

    # 单独对名字进行校验
    @validator('name')  # 对哪个字段校验就传入哪个字段名
    def name_must_alpha(cls, v):
        print(v)
        """判断name是否是字母，不是则报错"""
        assert v.isalpha(), 'must be alpha'
        # if not v.isalpha():
        #     raise ValidationError('must be alpha')
        return v


class Data(BaseModel):
    data: List[User]  # 类型嵌套,传入参数为 User类的数据列表


@app03.post('/getData')
async def get_data(data: Data):
    return data


@app03.post('/userInfo')
async def get_user(user: User):  # 通过User类进行校验
    print(user.name)
    print(user.dict())
    return user
